package com.hddznet.uniplatform.sm.config.cas;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hddznet.uniplatform.sm.vo.Result;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义失败处理器
 */
@Slf4j
@Component
public class CasAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    public CasAuthenticationFailureHandler() {
        log.info("CasAuthenticationFailureHandler loading ...");
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        /*
         * exception：错误信息（认证过程中的错误）
         */
        logger.error("Authentication does not pass");

        int status = HttpStatus.INTERNAL_SERVER_ERROR.value();
        response.setStatus(status);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().write(objectMapper.writeValueAsString(new Result<Object>("Authentication does not pass")));

    }
}
